// 实例CancelToken可以得到一个token
/**
 * token = {
 *    promise,
 *    reason,
 * }
 */

// new CancelToken(c => (cancel = c));
// cancel('message');

// cancel 一旦执行， 属性promise就会执行resolve，然后就会执行.then，而promise的then方法里取消axios

function CancelToken(executor) {
  if (typeof executor === 'function') {
    const token = this;

    let resolvePromise;

    token.promise = new Promise(resolve => {
      resolvePromise = resolve;
    });

    executor(function cancel(message) {
      token.reason = message;

      resolvePromise(token.reason);
    });
  }
}

CancelToken.source = function () {
  let cancel;

  const token = new CancelToken(c => (cancel = c));

  return {
    cancel,
    token
  };
};

// getCancelAndToken = CancelToken.source;
export default CancelToken.source;
